package org.jinxing.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jinxing.dao.ActionsInfoDAO;
import org.jinxing.dao.RoleActionRelationsDAO;
import org.jinxing.dao.RolesInfoDAO;
import org.jinxing.model.ActionsInfo;
import org.jinxing.model.ActionsInfoExample;
import org.jinxing.model.BooksInfo;
import org.jinxing.model.BooksInfoExample;
import org.jinxing.model.RoleActionRelations;
import org.jinxing.model.RoleActionRelationsExample;
import org.jinxing.model.RolesInfo;
import org.jinxing.model.UsersInfo;
import org.jinxing.service.RolesService;
import org.jinxing.service.UsersInfoService;
import org.jinxing.utils.JsonUtils;
import org.jinxing.utils.ModelUtils;
import org.jinxing.utils.RequestUtils;
import org.jinxing.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/r")
public class RoleController {
	protected static String className = RoleController.class.getName();
	protected static Log logger = LogFactory.getLog(className);//日志对象
	
	@Autowired
	UsersInfoService usersInfoService;
	@Autowired
	RolesService rolesService;
	@Autowired
	RolesInfoDAO rolesInfoDAO;
	@Autowired
	ActionsInfoDAO ActionsInfoDao;
	@Autowired
	RoleActionRelationsDAO roleActionRelationsDAO;
	
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>index<|><|><|>");
		return "/r/index";
	}
	
	@RequestMapping("/getRoles")
	public @ResponseBody String getRoles(HttpServletRequest request,HttpServletResponse response){
		logger.info("<|>"+className+"<|>getRoles<|><|><|>");
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		
		List<RolesInfo> list = rolesService.getAllRolesInfo();;
		int count = list.size();
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("Rows", list);
		result.put("Total", count);
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody String saveOrUpdate(HttpServletRequest request,HttpServletResponse response){
		String json = request.getParameter("json");
		Map<String,Object> result = new HashMap<String,Object>();
		List<Integer> successId = new LinkedList<Integer>();
		List tempList = JsonUtils.listFromJson(json);
		for(Object obj : tempList){
			RolesInfo role = ModelUtils.rolesFromJson(JsonUtils.jsonFromObject(obj));

			if(null == role.getId()){
				Integer id = this.rolesInfoDAO.insert(role);
				if(0 < id){
					successId.add(id);
				}
			}else{
				if(this.rolesInfoDAO.updateByPrimaryKey(role) == 1){
					successId.add(role.getId());
				}
			}
		}
		result.put("sucessList", successId);
		logger.info("<|>"+className+"<|>saveOrUpdate<|><|>"+successId+"<|>");
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/ra/{rid}")
	public String roleAction(HttpServletRequest request,HttpServletResponse response,Model model,@PathVariable Integer rid){
		logger.info("<|>"+className+"<|>roleAction<|><|><|>");
		model.addAttribute("role", this.rolesInfoDAO.selectByPrimaryKey(rid));
		RoleActionRelationsExample example = new RoleActionRelationsExample();
		example.createCriteria().andRoleidEqualTo(rid);
		Map<Integer,Integer> ownRole = new HashMap<Integer,Integer>();
		
		for(RoleActionRelations ra : this.roleActionRelationsDAO.selectByExample(example)){
			ownRole.put(ra.getActionid(), ra.getActionid());
		}
		
		model.addAttribute("treeHtml", this.getActionsInfo(0,ownRole));
		return "/r/ra";
	}
	
	protected StringBuffer getActionsInfo(Integer pid,Map<Integer,Integer> ownRole){
		ActionsInfoExample example = new ActionsInfoExample();
		example.createCriteria().andPidEqualTo(pid);
		StringBuffer buffer = new StringBuffer("");
		List<ActionsInfo> actionsInfoList = this.ActionsInfoDao.selectByExample(example);
		if(null==actionsInfoList || actionsInfoList.size() == 0){
			return buffer;
		}
		if(pid == 0){
			buffer.append("<ul id='treeUL'>");
		}else{
			buffer.append("<ul>");
		}
		for(ActionsInfo actions : actionsInfoList){
			if(ownRole.containsKey(actions.getId())){
				buffer.append("<li val='"+actions.getId()+"' ischecked='true'>");
			}else{
				buffer.append("<li val='"+actions.getId()+"'>");
			}
			buffer.append("<span>").append(actions.getName()).append("</span>");
			
			buffer.append(this.getActionsInfo(actions.getId(),ownRole).toString());
			buffer.append("</li>");
		}
		buffer.append("</ul>");
		return buffer;
	}
	
	@RequestMapping("/saveRA/{rid}")
	public @ResponseBody String saveRA(HttpServletRequest request,HttpServletResponse response,@PathVariable Integer rid){
		String namesStr = request.getParameter("names");
		Map<String,Object> result = new HashMap<String,Object>();
		List<Integer> successId = new LinkedList<Integer>();
		
		RoleActionRelationsExample raexample = new RoleActionRelationsExample();
		raexample.createCriteria().andRoleidEqualTo(rid);
		int delete = this.roleActionRelationsDAO.deleteByExample(raexample);
		logger.info("<|>"+className+"<|>saveOrUpdate<|>saveRA<|>"+delete+"<|>");
		
		String[] names = namesStr.split(";");
		for(String name : names){
			ActionsInfoExample example = new ActionsInfoExample();
			example.createCriteria().andNameEqualTo(name);
			ActionsInfo action = this.ActionsInfoDao.selectByExample(example).get(0);
			RoleActionRelations relation = new RoleActionRelations();
			relation.setActionid(action.getId());
			relation.setRoleid(rid);
			relation.setValid(1);
			this.roleActionRelationsDAO.insert(relation);
			
		}
		result.put("sucessList", successId);
		logger.info("<|>"+className+"<|>saveOrUpdate<|><|>"+successId+"<|>");
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/getMenu")
	public @ResponseBody String getMenu(HttpServletRequest request,HttpServletResponse response){
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		RolesInfo role = null;
		if(null != lgUser){
			role = this.rolesInfoDAO.selectByPrimaryKey(lgUser.getRoleid());
		}else{
			role = this.rolesInfoDAO.selectByPrimaryKey(7);
		}
		ActionsInfoExample example = new ActionsInfoExample();
		example.createCriteria().andTypeEqualTo(1);
		List<ActionsInfo> rootAtions = this.ActionsInfoDao.selectByExample(example);
		
		RoleActionRelationsExample newExample = new RoleActionRelationsExample();
		newExample.createCriteria().andRoleidEqualTo(role.getId());
		List<RoleActionRelations> relationList = this.roleActionRelationsDAO.selectByExample(newExample);
		
		List<ActionsInfo> resultList = new LinkedList<ActionsInfo>();
		
		for(ActionsInfo root : rootAtions){
			root.setChildren(new LinkedList<ActionsInfo>());
			for(RoleActionRelations inner : relationList){
				ActionsInfo innerActions = this.ActionsInfoDao.selectByPrimaryKey(inner.getActionid());
				if(root.getId().equals(innerActions.getPid())){
					root.getChildren().add(innerActions);
				}
			}
			if(root.getChildren().size() > 0){
				resultList.add(root);
			}
		}
		
		return JsonUtils.jsonFromObject(resultList);
	}
}
